<?php
/**
 * Description of settings
 *
 * @author iLyas
 */
class Settings extends CI_Controller {
	
	function __Constructor(){
		parent::__Constructor();
		
	    //check if user is logged in
        $this->is_logged_in();	
		
	}
	
   function index(){
        $this->load->model('user_model');
        $data['userInfo'] = $this->user_model->getUserRecords($this->session->userdata('user_id'));
       	$this->load->view('user/settings', $data);
   }
   
   function modify_settings(){
   	if ($this->input->post('submit'))
   		$this->validate_inputs();	
   }
   
   	function validate_inputs(){
        $this->load->library('form_validation');
	/*	
        //field name, error message, validation rules
        $this->form_validation->set_rules('user_name','Name','trim|required');
        $this->form_validation->set_rules('email_address','Email Address','trim|required|valid_email');
        $this->form_validation->set_rules('username','Username','trim|required|min_length[4]');
			
			if($this->form_validation->run() == FALSE )
				$this->index();
			else*/
				$this->apply_modifications();
   	}
	
	function apply_modifications(){
		$this->upload_avatar();
	}

	function upload_avatar(){
		$this->load->model('settings_model');
                
		$username = $this->session->userdata('username');
		(isset($username)) ? $pseudo = $username : $pseudo = 'coupain';
		
		$config['upload_path'] 			= './assets/img/avatar';
		$config['allowed_types']		= 'jpg';
		$config['max_size']			=  800;
		$config['remove_spaces']		= TRUE;
                $config['overwrite']                    = TRUE;
//		$config['max_width']			= '1024';
//		$config['max_height']			= '800';
		$config['file_name']			= $pseudo;

		$this->load->library('upload', $config);

		if (!$this->upload->do_upload()){
			$error_avatar = array('error_avatar_upload' => $this->upload->display_errors());
			$this->load->view('user/settings', $error_avatar);
		}else{
			//make thumb from image
			$image_data = $this->upload->data();
			
			$config['source_image'] 		= $image_data['full_path'];
			$config['new_image']			= './assets/img/avatar';
			$config['maintain_ratio'] 		= TRUE;
			$config['width'] 			= 96;
			$config['height'] 			= 96;
			
			$this->load->library('image_lib',  $config);
			if ($this->image_lib->resize()){
				//put information into db
				//$path_to_thumb = $image_data['full_path'];
				$path_to_thumb = base_url().'assets/img/avatar/'.$username.'.jpg';
				$this->settings_model->avatar_into_db($path_to_thumb, $username);
				//tell the view everything went ok
				$success_avatar = array('success_avatar_upload' => 'Uploaded successfuly!');
				$this->load->view('user/settings', $success_avatar);					
			}
			
		}
	}
	
	function rename_avatar(){
	}
	
	function is_logged_in(){
        $is_logged_in = $this->session->userdata('is_logged_in');
        
        if(!(isset($is_logged_in)) || $is_logged_in != TRUE){
             redirect('/user/login/', 'refresh');
        }
    }
}
?>